package app;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import app.EarningDate.ReportingTime;

public class ZacksEarningsProvider implements IEarningsProvider {
	
	SimpleDateFormat dateFormatter = new SimpleDateFormat("M/dd/yyyy", Locale.ENGLISH);
	
	@Override
	public Ticker getTicker(String symbol) throws ParseException, IOException {
		Ticker ticker = new Ticker(symbol);
		
		Document doc = Jsoup.connect("http://www.zacks.com/stock/research/" + symbol + "/earnings-announcements").get();
		Element earningTable = doc.select("#company_results").first();
		Elements earningRows = earningTable.select("tbody").first().select("tr"); 
		
		for (Element earningRow : earningRows) {
			Elements earningColumns = earningRow.select("td");
			
			String dateStr = earningColumns.get(0).text();
			Date date = dateFormatter.parse(dateStr);
			
			String typeStr = earningColumns.get(5).text(); 
			ReportingTime type = null;
			if (typeStr.equals("After Close")) {
				type = ReportingTime.AFTER_CLOSE;
			} else if (typeStr.equals("Before Open")) {
				type = ReportingTime.BEFORE_OPEN; 
			} else {
				type = ReportingTime.AFTER_CLOSE;
				//throw new ParseException("No valid reporting time type found.", 0);
			}
			
			EarningDate earningDate = new EarningDate(date, type);
			ticker.earningDates.add(earningDate);
		}
		
		return ticker;
	}

}
